﻿using System;
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using SqlSugar;
using XCPFrame.Core.ViewModels;
using XCPFrame.Core.Plugins;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using XCPFrame.Application.Http3thApi;
using System.Threading.Tasks;
using System.Net.Http;
using Furion.JsonSerialization;
using Furion.UnifyResult;
using StackExchange.Profiling.Internal;
using Furion;
using XCPFrame.Application.Services;
using XCPFrame.Application.Api;
using System.Text.RegularExpressions;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion.Internal;

namespace XCPFrame.Web.Entry.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly DemoService _service;
        private readonly DemoApiService _apiservice;
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IHttp _http;
        private readonly IJsonSerializerProvider _jsonSerializer;

        private readonly ISqlSugarRepository repository; // 仓储对象：封装简单的CRUD
        private readonly SqlSugarClient db; // 核心对象：拥有完整的SqlSugar全部功能


        public HomeController(ILogger<HomeController> logger, ISqlSugarRepository sqlSugarRepository,
            IHttpContextAccessor httpContextAccessor, IHttp http, IJsonSerializerProvider jsonSerializer)
        {
            _logger = logger;
            _service = new DemoService();
            _apiservice = new DemoApiService(sqlSugarRepository);
            _httpContextAccessor = httpContextAccessor;

            repository = sqlSugarRepository;
            db = repository.Context;

            _http = http;
            _jsonSerializer = jsonSerializer;
        }

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        public IActionResult Demo()
        {
            //memcached demo write in
            //MemcachedHelper.Set("abc", "我是缓存");
            //MemcachedHelper.Set("memcached", "memcached-core", "memcachedcore我是个缓存，我只能活30s。" + DateTime.Now, 30);

            return Content(_service.NormalDemo() + "----"+ _apiservice.GetDemo() + "---"+ App.Configuration["weixin:appid"]);
        }

        /// <summary>
        /// 数据库生成Models
        /// </summary>
        /// <returns></returns>
        //[AppAuthorize]
        public IActionResult InitDbModels()
        {
            _httpContextAccessor.HttpContext.Request.Headers["ResourceId"] = "";

            string path = Environment.CurrentDirectory.ToString().Substring(0, Environment.CurrentDirectory.ToString().Length- 9) + "Core/Models/Metas";
            //生成所有
            //db.DbFirst.IsCreateDefaultValue().CreateClassFile(path, "DT.Core.Models");
            //生成单表
            //db.DbFirst.Where(id).CreateClassFile(path, "DT.Core.Models");

            //修改实例名称规则
            foreach (var item in db.DbMaintenance.GetTableInfoList())
            {
                string entityName = StringHelper.ConvertClassNameString(item.Name);/*实体名驼峰*/
                db.MappingTables.Add(entityName, item.Name);
                foreach (var col in db.DbMaintenance.GetColumnInfosByTableName(item.Name))
                {
                    db.MappingColumns.Add(StringHelper.ConvertClassNameString(col.DbColumnName) /*类的属性驼峰*/, col.DbColumnName, entityName);
                }
            }
            db.DbFirst.IsCreateAttribute().CreateClassFile(path, "DT.Core.Models");

            return Content(path);
        }

        public IActionResult MemcachedRead()
        {

            string mh = ""; // (MemcachedHelper.Get("abc") == null) ? "无数据" : MemcachedHelper.Get("abc").ToString();

            return Content("ok:=cach:"+ mh);
        }

        public async Task<RESTfulResult<object>> GetAData()
        {
            UserViewModel user = new UserViewModel();
            user.loginCode = "admin";
            user.password = "343";
            var data = await _http.PostAAsync(user);
            return data;
        }

        public IActionResult DemoA()
        {
            string st = "null";
            //GetAwaiter().GetResult() 实例
            var temp = GetAData();

            st = temp.GetAwaiter().GetResult().Errors.ToString();

            //st = _jsonSerializer.Deserialize<RESTful>(st);

            return Content(st);
        }

        public IActionResult DemoB()
        {
            string st = "null";
            st = _http.GetBAsync().GetAwaiter().GetResult();
            return Content(st);
        }

        public IActionResult DemoC(string tb)
        {
            return Content("格式化：" + StringHelper.ConvertClassNameString(tb) );
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

        

    }
}
